#include "adc.h"
#include "ks0108.h"
#include "ffft.h"
#include "uart.h"
#include <avr/interrupt.h>

volatile uint8_t timer;

void adc_initial(void)
{
	DDRF = 0x60; // configure a2d port (PORTF) as input so we can receive analog signals 0x00
	PORTF = 0x00; // make sure pull-up resistors are turned off (else we��ll just read 0xCFF)
	
	sbi(ADCSRA,ADEN); // enables ADC by setting bit 7 (ADEN) in the ADCSRA
	cbi(ADCSRA,ADFR); // single sample conversion by clearing bit 5 (ADFR) in the ADCSRA
	ADCSRA = ((ADCSRA & 0b11111000) | 0b00000111); // clk/128 
	
	print("ADC initialized.\r\n");
	timer = 0;

}


void adc_capture (unsigned char channel, unsigned int *voltage)
{
	unsigned int i;
  ADMUX = 0x40 + channel;
//	ADMUX = 0xC0 + channel;	// selects single-ended conversion on pin PF0 ~ PF7 (ADC0 ~ ADC7)
							// selects AVCC as Vref
							// selects right adjust of ADC result
	sei();
	for (i = 0; i < FFT_N; i++)	// averaging the ADC results
	{
		while (timer != 1)
		{

		}
			sbi(ADCSRA,ADSC); // start a conversion by writing a one to the ADSC bit (bit 6)
		
			while(!(ADCSRA & 0b00010000)) // wait for conversion to complete: ADIF = 1
			{
				//sentchar1('.');		// for debugging
			}

		timer = 0;
		*voltage++ = ((ADCL) | (ADCH<<8)); //erst ADCL einlesen dann ADCH um 8bit nach rechts verschoben einlesen

	}
	cli();
}

void adc_fft (unsigned char channel)
{
	unsigned int i;
	unsigned int voltage[FFT_N];
	int16_t capture[FFT_N];			/* Wave capturing buffer */
	complex_t bfly_buff[FFT_N];		/* FFT buffer */
	uint16_t spektrum[FFT_N/2];		/* Spectrum output buffer */
	
	// ADC 5v to 10-bit digital (0x00 - 0x3FF)
	adc_capture(channel, voltage);

	// change 5v to +/-2.5v
	for (i = 0; i < FFT_N; i++)
	{		
		capture[i] = voltage[i] - 0x200;
	}

	// Fixed-point FFT routines for megaAVRs, (C)ChaN, 2005
	// http://www.embedds.com/avr-audio-spectrum-monitor-on-graphical-lcd/
	
	fft_input(capture, bfly_buff);
	fft_execute(bfly_buff);
	fft_output(bfly_buff, spektrum);
	
	// now show the results
//	lcd_print_signal(voltage);
	lcd_print_spectrum(spektrum);
}



